package com.ctg.itrdc.imageconsole.util;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctg.itrdc.imageconsole.common.util.PropertiesUtils;
import com.ctg.itrdc.pasp.security.api.dto.SystemRolesDTO;
import com.ctg.itrdc.pasp.security.utils.WebUtils;
import com.ctg.itrdc.paspsdk.common.utils.json.JSONUtils;


public class SysManagerUtil {	

	private static Logger logger = LoggerFactory.getLogger(SysManagerUtil.class);
	
	private final static String USERURLTEMPLATE = "http://{0}/ctg-sysmgr-portal-web/user";
	
	private final static String USERBYCODEURLTEMPLATE = "http://{0}/ctg-sysmgr-portal-web/user/byCode";
	
	private final static String QUERY_ROLE_BY_USER_API = "http://{0}/ctg-sysmgr-portal-web/system_roles/page/user2Roles";
	
	public static Long addUser(String sysManager, String sysUserCode, String password, Long staffId, String  sysCode) {
		// url
		String userUrl = MessageFormat.format(SysManagerUtil.USERURLTEMPLATE, sysManager);
		
		// post body
		Map<String, Object> user = new TreeMap<>();
		user.put("sysUserCode", sysUserCode);
		user.put("password", password);
		user.put("staffId", staffId);
		user.put("sysCode", sysCode);
		
		WebTarget target = ClientBuilder.newClient().target(userUrl);
		Response response = target.request()
				.post(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE));
		ResponseUtil.checkResponse(userUrl, response);
			
		return new JSONObject(response.readEntity(String.class)).getLong("data");
	}
	
	public static void deleteUser(String sysManager, Long sysUserId, Long staffId, String sysCode) {
		// url
		String userUrl = MessageFormat.format(SysManagerUtil.USERURLTEMPLATE, sysManager);
		
		
		WebTarget target = ClientBuilder.newClient().target(userUrl);
		Response response = target.queryParam("sysUserId", sysUserId).queryParam("staffId", staffId)
				.queryParam("sysCode", sysCode).request().delete();
		ResponseUtil.checkResponse(userUrl, response);
	}
		
	public static void updatePassword(String sysManager, Long sysUserId, String password, Long staffId, String sysCode) {
		// url
		String userUrl = MessageFormat.format(SysManagerUtil.USERURLTEMPLATE, sysManager);
		
		// post body
		Map<String, Object> user = new TreeMap<>();
		user.put("sysUserId", sysUserId);	
		user.put("password", password);
		user.put("staffId", staffId);
		user.put("sysCode", sysCode);
		
		WebTarget target = ClientBuilder.newClient().target(userUrl);
		Response response = target.request()
				.put(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE));
		ResponseUtil.checkResponse(userUrl, response);
	}
	
	public static JSONObject getUserById(String sysManager, Long sysUserId) {
		// url
		String userUrl = MessageFormat.format(SysManagerUtil.USERURLTEMPLATE, sysManager);
		
		WebTarget target = ClientBuilder.newClient().target(userUrl);
		Response response = target.queryParam("sysUserId", sysUserId)
				.request().get();
		ResponseUtil.checkResponse(userUrl, response);
		return new JSONObject(response.readEntity(String.class)).getJSONObject("data");
	}
	
	public static JSONObject getUserByCode(String sysManager, String sysUserCode) {
		// url
		String userByCodeUrl = MessageFormat.format(SysManagerUtil.USERBYCODEURLTEMPLATE, sysManager);
		
		WebTarget target = ClientBuilder.newClient().target(userByCodeUrl);
		Response response = target.queryParam("sysUserCode", sysUserCode)
				.request().get();
		ResponseUtil.checkResponse(userByCodeUrl, response);
		return new JSONObject(response.readEntity(String.class)).getJSONObject("data");
	}
	
	/**
	 * 判断当前用户是否为管理员
	 * @return
	 */
	public static boolean isRoleOfDockerManager() {
		try {
			Long userId = WebUtils.getCtgUser().getSysUserId();
			// 目前容器控制台的管理员角色编码是配置在config文件中的，系统权限管理上配置的角色编码需与此一致。
			// 从本项目的配置文件中查出配置好的容器控制台管理员角色的角色编码
			String dockerManagerRoleCode = PropertiesUtils.getConfigValueCache("config", "docker.manager.role.code");
			// 查出当前用户的角色编码
			String roleCodeOfCurrentUser = getRoleCodeByUserId(userId);
			if (StringUtils.isEmpty(roleCodeOfCurrentUser)) {
				throw new RuntimeException("获取当前用户所属角色异常，请联系管理员！");
			} else if (dockerManagerRoleCode.equals(roleCodeOfCurrentUser)) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			logger.error("判断当前用户是否为管理员时出现异常", e);
			throw new RuntimeException(e.getMessage());
		}
	}
	
	@SuppressWarnings("unchecked")
	private static String getRoleCodeByUserId(Long userId) {
		String sysManagerIpPort = PropertiesUtils.getConfigValueCache("config", "sysManager.endpoint");
		String apiUrl = MessageFormat.format(QUERY_ROLE_BY_USER_API, sysManagerIpPort);
		
		WebTarget target = ClientBuilder.newClient().target(apiUrl);
		Response response = target.queryParam("sysUserId", userId).request()
				.post(Entity.entity(new SystemRolesDTO(), MediaType.APPLICATION_JSON_TYPE));
		ResponseUtil.checkResponse(apiUrl, response);
		Map<String, Object> map = JSONUtils.jsonToMap(response.readEntity(String.class));
		Map<String, Object> dataMap = (Map<String, Object>) map.get("data");
		List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("list");
		for(Map<String, Object> mapOfList : list) {
			if (mapOfList.containsKey("sysUserRoleId")) {
				return (String) mapOfList.get("sysRoleCode");
			}
		}
		return null;
	}
	
}
